import React, { useState } from 'react';
import { COMMENTS } from './data';

const CommentApp = () => {
  const [name, setName] = useState('');
  const [msg, setMsg] = useState('');
  const [rating, setRating] = useState();
  const [comment, setComments] = useState(COMMENTS);
  const [filterCondition, setFilterCondition] = useState('ALL');
  function handleNameChange(e) {
    setName(e.target.value);
  }
  function handleMsgChange(e) {
    setMsg(e.target.value);
  }
  function handleRatingChange(e) {
    setRating(Number(e.target.value));
  }

  function submit() {
    const newComments = comment.concat({
      id: comment.length + 1,
      name,
      rating,
      msg,
    });
    setComments(newComments);
    setName('');
    setMsg('');
    setRating('');
  }

  function handleFiterConditionChangeToAll() {
    setFilterCondition('ALL');
    console.log(filterCondition);
  }

  function handleFiterConditionChangeToGood() {
    setFilterCondition('Good');
  }
  function handleFiterConditionChangeToMedium() {
    setFilterCondition('Medium');
  }
  function handleFiterConditionChangeToBad() {
    setFilterCondition('Bad');
  }

  const commentsWithFilter = comment.filter((comment) => {
    console.log(comment);
    if (filterCondition === 'Good') {
      return comment.rating >= 4;
    } else if (filterCondition === 'Medium') {
      return comment.rating >= 2 && comment.rating < 4;
    } else if (filterCondition === 'Bad') {
      return comment.rating < 2;
    } else {
      return true;
    }
  });
  return (
    <div data-testid="app" className="app">
      用户：<input value={name} onChange={handleNameChange} type="text"></input>
      <br />
      评分：<input value={rating} onChange={handleRatingChange} type="text"></input>
      <br />
      评论：<textarea value={msg} onChange={handleMsgChange}></textarea>
      <br />
      <button onClick={submit}>提交</button>
      <br />
      <button onClick={handleFiterConditionChangeToAll}>全部</button>
      <button onClick={handleFiterConditionChangeToGood}>好评</button>
      <button onClick={handleFiterConditionChangeToMedium}>中评</button>
      <button onClick={handleFiterConditionChangeToBad}>差评</button>
      <ul>
        {commentsWithFilter.map((item) => (
          <li>
            {item.name} Rating : {item.rating}
            <br />
            {item.msg}{' '}
          </li>
        ))}
      </ul>
    </div>
  );
};

export default CommentApp;
